package com.umeox.watch.moto.sos.utils;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import com.umeox.moto.common.log.Logger;

/**
 * Created by Rambo 2025/5/14/星期三
 * Describe:
 */
public class MicrophoneUtils {

    public static boolean isMicrophoneInUse() {
        AudioRecord recorder = null;
        try {
            int bufferSize = AudioRecord.getMinBufferSize(44100,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT);

            recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                    44100,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    bufferSize);

            if (recorder.getState() != AudioRecord.STATE_INITIALIZED) {
                return true; // 麦克风可能被占用
            }

            recorder.startRecording();
            if (recorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
                Logger.e("Microphone is in use");
                return true; // 麦克风可能被占用
            }

            return false;
        } catch (Exception e) {
            Logger.e("Microphone is in use" + e.getMessage());
            return true; // 出现异常，麦克风可能被占用
        } finally {
            if (recorder != null) {
                recorder.stop();
                recorder.release();
            }
        }
    }
}
